package com.share.common.tools.bean;

import org.apache.log4j.Logger;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;

public class BeanUtils {

    private static final Logger logger = Logger.getLogger(BeanUtils.class);

    /**
     * bean 转化为实体
     *
     * @param bean 被转换的对象
     * @return 返回集合
     */
    public static HashMap<String, Object> beanToMap(Object bean) {
        HashMap<String, Object> map = new HashMap<>();
        if (null == bean) {
            return map;
        }
        Class<?> clazz = bean.getClass();
        BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo(clazz);

            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : descriptors) {
                String propertyName = descriptor.getName();
                if (!"class".equals(propertyName)) {
                    Method method = descriptor.getReadMethod();
                    Object result;
                    result = method.invoke(bean);
                    if (null != result) {
                        map.put(propertyName, result);
                    } else {
                        map.put(propertyName, "");
                    }
                }
            }
        } catch (Exception e) {
            logger.error("对象转换成map集合时候出错");
            logger.error(e.getStackTrace());
            logger.error(e.getMessage());
            logger.error(e.getLocalizedMessage());
        }
        return map;
    }

    /**
     * map 转化为 bean
     *
     * @param clazz 转换的类
     * @param map   集合
     * @return 该对象
     */
    public static Object mapToBean(Class clazz, HashMap map) {
        Object object = null;
        try {
            object = clazz.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : descriptors) {
                String propertyName = descriptor.getName();
                if (map.containsKey(propertyName)) {
                    Object value = map.get(propertyName);
                    Object[] args = new Object[1];
                    args[0] = value;
                    descriptor.getWriteMethod().invoke(object, args);
                }
            }

        } catch (Exception e) {
            logger.error("map转换成对象时候出错");
            logger.error(e.getStackTrace());
            logger.error(e.getMessage());
            logger.error(e.getLocalizedMessage());
        }
        return object;
    }
}
